local LimitBuyConfig = require("excel.Shop").limitBuy
local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local InnerDataManagerFW = require("innerdata.InnerDataManagerFW")
local InnerDataDefine = require("innerdata.Define")

LIMIT_BUY_REMAIN_CNT = LIMIT_BUY_REMAIN_CNT or {}


function init()
    LuaMongo.find(DB.db_server, {limitBuyCnt = "limitBuyCnt"})
    while true do
        local tmp = {}
        if not LuaMongo.next(tmp) then
            break
        end
        if tmp.limitBuyCnt then
            LIMIT_BUY_REMAIN_CNT = tmp
        end
    end
    if not LIMIT_BUY_REMAIN_CNT[1] then
        for i=1, #LimitBuyConfig do
            LIMIT_BUY_REMAIN_CNT[i] = 0
        end
    end
    if #LIMIT_BUY_REMAIN_CNT < #LimitBuyConfig then
      for i=#LimitBuyConfig - #LIMIT_BUY_REMAIN_CNT, #LimitBuyConfig do
        LIMIT_BUY_REMAIN_CNT[i] = 0
      end
    end
    InnerDataManagerFW.Send2LInnerData(nil, InnerDataDefine.INNERDATA_TYPE_SHOP_LIMIT_BUY, LIMIT_BUY_REMAIN_CNT)
end


function updateCnt()
    LIMIT_BUY_REMAIN_CNT.limitBuyCnt = "limitBuyCnt"
    LuaMongo.update(DB.db_server, {limitBuyCnt = "limitBuyCnt"}, LIMIT_BUY_REMAIN_CNT, true)
    --  LuaMongo.remove(DB.db_server, {limitBuyCnt = nil})
    --  LuaMongo.insert(DB.db_server, {limitBuyCnt = LIMIT_BUY_REMAIN_CNT})
end

function buyItem(human, oType, info)
    LIMIT_BUY_REMAIN_CNT[info.index] = LIMIT_BUY_REMAIN_CNT[info.index] + info.cnt
    local data = {}
    for i=1, #LIMIT_BUY_REMAIN_CNT do
      data[i] = LIMIT_BUY_REMAIN_CNT[i]
    end
    data.uuid = human._id
    InnerDataManagerFW.Send2LInnerData(nil, InnerDataDefine.INNERDATA_TYPE_SHOP_LIMIT_BUY, data)
end

InnerDataManagerFW.Register(InnerDataDefine.INNERDATA_TYPE_SHOP_LIMIT_BUY, buyItem)
